package transpose

import (
	"strings"
)

const testVersion = 1

func Transpose(input []string) (results []string) {
	if len(input) == 0 {
		return []string{}
	}

	// find longest sentence of 'input' and make it's len(sentence)
	oriI := len(input)
	oriJ := 0
	for i := 0; i < oriI; i++ {
		if len(input[i]) > oriJ {
			oriJ = len(input[i])
		}
	}

	// make matrix([][]string) and put 'input' into it
	origins := make([][]string, oriI)
	for i := 0; i < len(input); i++ {
		origins[i] = make([]string, oriJ)
		for j := 0; j < len(input[i]); j++ {
			origins[i][j] = input[i][j : j+1]
		}
	}

	// create reverse matrix
	originsReversal := make([][]string, oriJ)
	for i := 0; i < oriJ; i++ {
		originsReversal[i] = make([]string, oriI)
	}

	// put 'origins' into reversal matrix
	for i := 0; i < oriI; i++ {
		for j := 0; j < oriJ; j++ {
			if origins[i][j] == "" {
				originsReversal[j][i] = " "
			} else {
				originsReversal[j][i] = origins[i][j]
			}
		}
	}

	//
	for i := 0; i < oriJ; i++ {
		results = append(results, strings.Join(originsReversal[i], ""))
	}

	// check last sentence
	lastSentence := results[oriJ-1]
	for i := 1; i < len(lastSentence); i++ {
		if lastSentence[i:i+1] == " " && lastSentence[i-1:i] != " " {
			results[oriJ-1] = lastSentence[0:i]
			break
		}
	}

	return
}
